package com.shujia.login;

import com.shujia.utils.CodeModel;
import com.shujia.utils.CodeTool;
import com.shujia.utils.MySQLTool;
import redis.clients.jedis.Jedis;

import java.sql.*;
import java.util.Scanner;
import java.util.Set;

/*
    登录注册的案例
 */
public class LoginDemo {
    private static boolean flag = false;

    public static void main(String[] args) {
        //首页
        init();

    }

    public static void init() {
        System.out.println("================欢迎进入尚平京东商城 ^ _ ^================");
        System.out.print("请选择您要做的操作：（1.登录  2.注册  3.忘记密码）:");
        Scanner sc = new Scanner(System.in);
        String choice = sc.nextLine();
        switch (choice) {
            case "1":
                login();
                break;
            case "2":
                register();
                break;
            case "3":
                //TODO: 忘记密码
                break;
            default:
                System.out.println("没有该选项，已退出....");
                break;
        }

        //判断是否登录成功！！。·
        //如果登录成功！查询商品数据
        if (flag) {
            try {
                selectGoods();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("欢迎下次访问...");
        }
    }

    public static void selectGoods() throws Exception{
        System.out.println("---------------------------------------------------");
        System.out.println("查询方式：（1.根据详细商品名称查询(redis缓存)  2.根据品牌查询(redis充当二级索引)）");
        System.out.println("---------------------------------------------------");
        Scanner sc = new Scanner(System.in);
        String choice = sc.next();
        if("1".equals(choice)){
            selectGoodsWithGname();
        }else if("2".equals(choice)){
            System.out.print("请输入您要查询电脑的品牌：(联想，华为)");
            String brand = sc.next();
            Jedis jedis = new Jedis("192.168.220.100", 12346);
            Connection conn = MySQLTool.getMySqlConnection();
            Statement state = conn.createStatement();
            Set<String> ids = jedis.smembers("电脑:" + brand);
            System.out.println(brand+"电脑信息如下：");
            System.out.println("==================================================================================");
            for (String id : ids) {
                ResultSet resultSet = state.executeQuery("select gname,price,commit,shop,icons from jd_goods where id=" + id);
                while (resultSet.next()){
                    String gname = resultSet.getString("gname");
                    String price = resultSet.getString("price");
                    String commit = resultSet.getString("commit");
                    String shop = resultSet.getString("shop");
                    String icons = resultSet.getString("icons");
                    String info = gname+"|"+price+"|"+commit+"|"+shop+"|"+icons;
                    System.out.println(info);
                    System.out.println("---------------------------------------------------------------");
                }
            }
        }else {
            System.out.println("没有其他查询方式！");
        }
    }



    //Redis当作缓存，mysql查询案例
    public static void selectGoodsWithGname() {
        Connection conn = null;
        Statement state = null;
        Jedis jedis = null;


        Scanner sc = new Scanner(System.in);
        System.out.println("**********************************");
        System.out.println("**********欢迎来到商城首页！**********");
        System.out.println("***********************************");
        System.out.print("请输入您要查询的商品：");
        String good = sc.nextLine(); //华为MateBook D 14 SE 2024笔记本电脑 13代酷睿/14英寸护眼全面屏/轻薄办公本 i5 16G 1T 深空灰

        //先查询redis,如果redis中有该商品，直接详细商品信息返回给用户
        //如果没有，就去查询mysql业务数据库
        //查到后，将详细商品信息返回给用户的同时，向redis中添加一条该数据，并设置过期时间
        try {
            conn = MySQLTool.getMySqlConnection();
            state = conn.createStatement();
            jedis = new Jedis("192.168.220.100", 12346);
            boolean exists = jedis.exists(good);
            // 华为MateBook D 14 SE 2024笔记本电脑 13代酷睿/14英寸护眼全面屏/轻薄办公本 i5 16G 1T 深空灰
            // ￥4199.00
            // 2万+条评价
            // 华为京东自营官方旗舰店
            // 自营
            if (exists) {
                //去redis查询
                System.out.println("走redis查询的结果...");
                String s = jedis.get(good);
                System.out.println("商品详细信息如下：");
                System.out.println("==================================================================================");
                System.out.println(s);
                System.out.println("==================================================================================");

            } else {
                //去mysql查询
                System.out.println("走mysql查询的结果...");
                String sql = "select gname,price,commit,shop,icons from jd_goods where gname='"+good+"'";
                System.out.println(sql);
                ResultSet resultSet = state.executeQuery(sql);
                if(resultSet.next()){
                    String gname = resultSet.getString("gname");
                    String price = resultSet.getString("price");
                    String commit = resultSet.getString("commit");
                    String shop = resultSet.getString("shop");
                    String icons = resultSet.getString("icons");
                    System.out.println("商品详细信息如下：");
                    System.out.println("==================================================================================");
                    String info = gname+"|"+price+"|"+commit+"|"+shop+"|"+icons;
                    System.out.println(info);
                    System.out.println("==================================================================================");

                    jedis.set(gname,info);
                    jedis.expire(gname,86400);
                    System.out.println("redis更新完毕");
                }else {
                    System.out.println("发生了redis穿透的现象！请联系管理员，及时维护！");
                }

            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (state != null) {
                try {
                    state.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    public static void register() {
        Connection conn = null;
        Statement state = null;
        Jedis jedis = null;
        try {
            Scanner sc = new Scanner(System.in);
            System.out.println("**************** 注册页面 *****************");
            while (true) {
                System.out.print("请输入您注册用户名: ");
                String username = sc.next();
                //先查询数据库，判断该用户是否存在
                //使用工具类获取连接对象
                conn = MySQLTool.getMySqlConnection();
                state = conn.createStatement();
                jedis = new Jedis("192.168.220.100", 12346);
                //select id from users where username='xiaohu';
                ResultSet resultSet = state.executeQuery("select name,password from users where name='" + username + "'");
                if (resultSet.next()) {
                    System.out.println("该用户名已被注册！！请重新输入！");
                } else {
                    System.out.print("请输入您注册密码: ");
                    String password = sc.next();

                    System.out.print("请输入您注册手机号: ");
                    String phoneNumber = sc.next();

                    //TODO: 检查手机号是否重复
                    ResultSet resultSet2 = state.executeQuery("select name,password from users where phoneNumber='" + phoneNumber + "'");
                    if (resultSet2.next()) {
                        System.out.println("该手机号已被注册！！程序已经停止退出...");
                        return; // 结束整个方法
                    }

                    //TODO：验证码发送过程
                    String code = CodeTool.sendCode(phoneNumber, CodeModel.REGISTER_MODEL);
                    //TODO: 向redis中添加一个，并设置过期时间
                    long timeMillis = System.currentTimeMillis();
                    jedis.set(phoneNumber + "_" + timeMillis, code);
                    jedis.expire(phoneNumber + "_" + timeMillis, 300);

                    while (true) {
                        System.out.print("请输入6位验证码: ");
                        String yzm = sc.next();
                        String redis_yzm = jedis.get(phoneNumber + "_" + timeMillis);
                        if (redis_yzm == null) {
                            System.out.println("验证码已经失效....");
                            break;
                        }

                        if (redis_yzm.equals(yzm)) {
                            int i = state.executeUpdate("insert into users(name,password,phoneNumber) values('" + username + "','" + password + "','" + phoneNumber + "')");
                            if (i == 1) {
                                System.out.println(username + "用户注册成功！！");
                            } else {
                                System.out.println("注册失败！");
                            }
                            break;
                        } else {
                            System.out.println("与发送的验证码不一致，重新输入！");
                        }
                    }
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (state != null) {
                try {
                    state.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void login() {
        Connection conn = null;
//        Statement state = null;
        PreparedStatement state = null;
        Jedis jedis = null;


        try {
            //先查询数据库，判断该用户是否存在
            //使用工具类获取连接对象
            conn = MySQLTool.getMySqlConnection();
//            state = conn.createStatement();
            //为了解决sql注入的问题，在创建数据库操作对象的时候，改为创建预编译对象
            //建议：将来遇到查询的需求的话，建议使用预编译对象进行查询
            state = conn.prepareStatement("select name,password from users where name=?");
            jedis = new Jedis("192.168.220.100", 12346);
            Scanner sc = new Scanner(System.in);
            System.out.println("**************** 登录页面 （1.账号密码登录  2.手机验证码登录）*****************");
            String choice = sc.nextLine();
            switch (choice) {
                case "1":
                    System.out.print("请输入您的用户名: ");
                    String username = sc.nextLine();
                    System.out.print("请输入您的密码: ");
                    String password = sc.nextLine();
                    //select id from users where username='xiaohu';
                    //select name,password from users where name='asd' or '1'='1'
//                    ResultSet resultSet = state.executeQuery("select name,password from users where name='" + username + "'");
                    state.setString(1,username);
                    ResultSet resultSet = state.executeQuery();
                    if (resultSet.next()) {
                        String pwd = resultSet.getString("password");
                        if (password.equals(pwd)) {
                            System.out.println("登录成功！！请联系管理员尚平查询商品....");
                            flag = true;
                        }
                    } else {
                        System.out.println("该用户还未进行注册，请先注册！！");
                    }
                    break;
                case "2":
                    System.out.print("请输入您的手机号: ");
                    String phoneNumber = sc.next();
                    //TODO: 检查手机号是否重复
                    ResultSet resultSet2 = state.executeQuery("select name,password from users where phoneNumber='" + phoneNumber + "'");
                    if (resultSet2.next()) {
                        //TODO：验证码发送过程
                        String code = CodeTool.sendCode(phoneNumber, CodeModel.LOGIN_MODEL);
                        //TODO: 向redis中添加一个，并设置过期时间
                        long timeMillis = System.currentTimeMillis();
                        jedis.set(phoneNumber + "_" + timeMillis, code);
                        jedis.expire(phoneNumber + "_" + timeMillis, 60);

                        while (true) {
                            System.out.print("请输入6位登录验证码: ");
                            String yzm = sc.next();
                            String redis_yzm = jedis.get(phoneNumber + "_" + timeMillis);
                            if (redis_yzm == null) {
                                System.out.println("验证码已经失效....");
                                break;
                            }

                            if (redis_yzm.equals(yzm)) {
                                System.out.println("登录成功！！请联系管理员尚平查询商品....");
                                flag = true;
                                break;
                            } else {
                                System.out.println("与发送的验证码不一致，重新输入！");
                            }
                        }
                    } else {
                        System.out.println("该手机号还未注册！！");
                    }
                    break;
                default:
                    System.out.println("没有该登录选项！");
                    break;

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (state != null) {
                try {
                    state.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
